<?php
namespace app\admin\logic;

use app\common\exception\LogicException;
use app\common\logic\EncryptLogic;
use app\model\Admin;
use app\model\AdminToken;

/**
 * 登录业务逻辑类
 */
class AuthLogic
{
    /**
     * @Description 登录
     * @author: zj
     * @param string $username
     * @param string $password
     * @time 2024/03/07 17:20:48
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login (string $username, string $password) :array
    {
        //获取用户信息，判断用户是否存在
        $adminModel = new Admin();

        $adminInfo = $adminModel
            ->field('id,name,password,salt,phone,status')
            ->where('name', $username)
            ->where('delete_time', $adminModel::IS_DELETE_NO)
            ->find();
        if (!$adminInfo) {
            throw new LogicException('账号密码不匹配');
        }

        //验证密码是否正确
        $this->checkPassword($password, $adminInfo['password'], $adminInfo['salt']);

        //创建token
        $token = $this->createToken($adminInfo['name']);

        //把用户数据保存到缓存
        $tokenData = [
            'token' => $token,
            'admin_info' => [
                'admin_id' => $adminInfo['id'],
                'name' => $adminInfo['name'],
                'phone' => $adminInfo['phone'],
            ],
        ];

        //保存token值
        $adminTokenModel = new AdminToken();
        $oldTokenInfo = $adminTokenModel
            ->where('admin_id', $adminInfo['id'])
            ->field('id,token')
            ->find();
        if ($oldTokenInfo) {
            $adminTokenModel->updateToken($oldTokenInfo['id'], $token);
            //删除就token缓存数据
            cache()->delete($oldTokenInfo['token']);
        } else {
            $adminTokenModel->addToken($adminInfo['id'], $token);
        }

        //加入缓存一天
        $set = cache()->set($token, json_encode($tokenData, JSON_UNESCAPED_UNICODE), 86400);
        if (!$set) {
            throw new LogicException('缓存登录数据失败');
        }

        return $tokenData;
    }

    /**
     * @Description 检查密码
     * @author: zj
     * @param string $password
     * @param string $passwordMD5
     * @param string $salt
     * @time 2024/03/07 17:21:44
     * @return true
     */
    public function checkPassword(string $password, string $passwordMD5, string $salt)
    {
        $encrypt = new EncryptLogic();
        $encryptPassword = $encrypt->encryptMD5($password, $salt);
        if ($encryptPassword != $passwordMD5) {
            throw new LogicException('账号密码不匹配');
        }

        return true;
    }

    /**
     * @Description 创建token
     * @author: zj
     * @param string $username
     * @time 2024/03/07 17:21:58
     * @return string
     */
    public function createToken(string $username)
    {
        return md5($username. request()->time());
    }

    /**
     * @Description 路由数组建使用title名称
     * @author: zj
     * @param array $rules
     * @time 2024/03/07 17:22:11
     * @return array
     */
    public function ruleArrayKeyUseTitle (array $rules)
    {
        $newRules = [];
        foreach ($rules as $v) {
            $newRules[$v['title']] = $v['route'];
        }

        return $newRules;
    }

    /**
     * @Description 退出登录
     * @author: zj
     * @param string $token
     * @time 2024/03/05 11:59:03
     * @return true
     */
    public function logout(string $token)
    {
        cache()->delete($token);

        return true;
    }
}
